<?php
namespace App\Models;

use App\Models\Order;
use App\Models\Dangerous;

class Elsearch {
	public $_client = null;
    public function __construct(){
        $this->_client = \Elasticsearch\ClientBuilder::create()->build();
    }
    public function rebuild_search_dangerous(){
    	$dangerous_model = new dangerous();
    	$cnt = $dangerous_model->count_dangerous();
    	$size = 1;
    	$step = round($cnt/$size)+1;
    	for($i = 1;$i<=$step;$i++){
            $rtn = $dangerous_model->dangerous_list('dangerous.id',$i,$size);
            if($rtn){
            	$rtn = $rtn->toarray();
            	$params = array();
            	foreach ($rtn as $key => $value) {
            		$id = $value->id;
            		$keyword = $value->xl_name.';'.$value->zh_name.';'.$value->alias;
            		$dangerous_id = $value->dangerous_id;
            		// echo $keyword;
            		// print_rf($value);die();	
            		$params['body'][] = [ 'index' => [ '_index' => 'search_dangerous', '_type' => 'dangerous_keywords', '_id' =>$id ] ];
		            $params['body'][] = [ 
		                                    'index_id' => $id, 
		                                    'dangerous_id' => $dangerous_id,
		                                    'keywords' => $keyword,
		                                    'name' => $value->xl_name,
		                                ]; 
            	}
            	if($params){
            		$responses = $this->_client->bulk($params);	
            	}
            }
        }
    }

    function search_dangerous($keyword,$page,$size){  
        $start = $page * $size;
        
        $params = [
            'index' => 'search_dangerous',
            'type' => 'dangerous_keywords',
            'body' => [
                'query' => [
		            'bool' => [
		                'must' => [
		                    [ 'match' => [ 'keywords' => $keyword ] ],
		                    // [ 'match' => [ 'testField2' => 'xyz' ] ],
		                ]
		            ]
		        ],
                'from' => $start,  // 分页
                'size' => $size  // 每页数量
            ]
        ];

        $response = $this->_client->search($params);
        return $response['hits'];

    }  
}